package com.bidevalution.controller.api;

import com.bidevalution.business.context.ParamsType;
import com.bidevalution.business.context.SysIdentityCode;
import com.bidevalution.business.service.BeExpertSpecialityService;
import com.bidevalution.business.service.BeSectionExpertInfoService;
import com.bidevalution.business.service.BeSectionInfoService;
import com.bidevalution.business.service.BeSysIdentityService;
import com.bidevalution.controller.dto.BeSectionExpertInfoDTO;
import com.bidevalution.controller.util.RequestUtil;
import com.bidevalution.dao.entity.BeExpertInfo;
import com.bidevalution.dao.entity.BeExpertSpeciality;
import com.bidevalution.dao.entity.BeSectionExpertInfo;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSysParams;
import com.bidevalution.dao.mapper.BeSysParamsMapper;
import com.bidevalution.service.EntInfoService;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.context.RedisKeyConstants;
import com.bidevalution.support.exception.BizException;
import com.bidevalution.support.util.StringUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qtp.common.core.TSUser;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.model.Response;
import com.qtp.core.redis.RedisUtil;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 专家设置控制层
 * Created by glodon on 2019-08-08.
 */
@Log4j2
@RestController
@RequestMapping("/BeSectionExpertInfo")
@Api(tags = "标段专家设置")
public class BeSectionExpertInfoController extends BaseController{
    @Autowired
    private BeSectionExpertInfoService beSectionExpertInfoService;
    @Autowired
    private BeExpertSpecialityService beExpertSpecialityService;
    @Autowired
    private EntInfoService entInfoService;
    @Autowired
    private BeSectionInfoService beSectionInfoService;
    @Autowired
    private BeSysParamsMapper beSysParamsMapper;
    @Autowired
    private BeSysIdentityService beSysIdentityService;
    @Value("${expert.generateMobile}")
    private String generateMobile;
    @Value("${expert.identityThirdCheck}")
    private String identityThirdCheck;
    private Logger log =Logger.getLogger(getClass());
    @RequestMapping("/getExpertSpecialityList")
    @ApiOperation(value = "专家设置-获取专家专业列表", response = BeExpertSpeciality.class, httpMethod = "GET")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "parentId", value = "父节点ID", required = true)
            })
    public Response<List<Map<String, Object>>> getExpertSpecialityList(@RequestParam("parentId") Integer parentId) {
        try {
        	Map<String,Object> dataMap;
        	List<Map<String, Object>> dataList = Lists.newArrayList();
        	for(BeExpertSpeciality beExpertSpeciality:beExpertSpecialityService.selectChildList(parentId)) {
        		dataMap = Maps.newHashMap();
        		dataMap.put("value", beExpertSpeciality.getId());
        		dataMap.put("label", beExpertSpeciality.getName());
        		dataList.add(dataMap);
        	}
            return Response.ok(dataList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("获取专家专业列表失败");
        }
    }
    @RequestMapping("/getExpertListBySectionId")
    @ApiOperation(value = "专家设置-根据标段ID获取专家信息列表", response = BeSectionExpertInfo.class, httpMethod = "GET")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "sectionId", value = "标段id", required = true)
            })
    public Response<List<BeSectionExpertInfo>> getExpertListBySectionId(@RequestParam("sectionId") String sectionId) {
        try {
            return Response.ok(beSectionExpertInfoService.getExpertListBySectionId(sectionId,"0",null));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("根据标段ID获取专家信息列表失败");
        }
    }

    @RequestMapping("/getAllExpertListBySectionId")
    @ApiOperation(value = "专家设置-根据标段ID获取专家信息列表", response = BeSectionExpertInfo.class, httpMethod = "GET")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "sectionId", value = "标段id", required = true)
            })
    public Response<List<BeSectionExpertInfo>> getAllExpertListBySectionId(@RequestParam("sectionId") String sectionId) {
        try {
            return Response.ok(beSectionExpertInfoService.getAllExpertListBySectionId(sectionId));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("根据标段ID获取专家信息列表失败");
        }
    }

    @RequestMapping("/saveExpertInfo")
    @ApiOperation(value = "专家设置-保存专家信息", response = Response.class, httpMethod = "POST")

    public Response saveExpertInfo(BeSectionExpertInfoDTO beSectionExpertInfoDTO) {
        try {


            BeSectionExpertInfo beSectionExpertInfo = new BeSectionExpertInfo();
            beSectionExpertInfo.setSeqId(IdsUtil.uuid());
            beSectionExpertInfo.setSectionId(beSectionExpertInfoDTO.getSectionId());
            beSectionExpertInfo.setCardNo(beSectionExpertInfoDTO.getCardNo());
            beSectionExpertInfo.setName(beSectionExpertInfoDTO.getName());
            beSectionExpertInfo.setLoginName(beSectionExpertInfoDTO.getLoginName());
            beSectionExpertInfo.setWorkUnit(beSectionExpertInfoDTO.getWorkUnit());
            if("1".equals(generateMobile)) {
            	String value = beSysIdentityService.getValue(SysIdentityCode.MobileCode);
            	beSectionExpertInfo.setPhone(StringUtil.getLenString(value,11,"0"));
            }else {
            	beSectionExpertInfo.setPhone(beSectionExpertInfoDTO.getPhone());
            }
            
            beSectionExpertInfo.setExpertType(beSectionExpertInfoDTO.getExpertType());
            beSectionExpertInfo.setAreaType(beSectionExpertInfoDTO.getAreaType());
            beSectionExpertInfo.setIsAvoid(Constants.ZERO);
            beSectionExpertInfo.setIsManager(Constants.ZERO);
            beSectionExpertInfo.setCreateTime(DateUtil.now());
            beSectionExpertInfo.setUpdateTime(DateUtil.now());
            beSectionExpertInfo.setExpertSource(beSectionExpertInfoDTO.getExpertSource());
            List<BeSysParams> beSysParamList = beSysParamsMapper.selectForList(ParamsType.expertSource.name());
            for(BeSysParams beSysParams:beSysParamList) {
            	if(beSysParams.getSypaValue().equals(String.valueOf(beSectionExpertInfo.getExpertSource()))) {
                    beSectionExpertInfo.setExpertSourceName(beSysParams.getSypaName());
                    break;
            	}
            }
            beSectionExpertInfo.setFirstSpeciality(beSectionExpertInfoDTO.getFirstSpeciality());
            beSectionExpertInfo.setSecondSpeciality(beSectionExpertInfoDTO.getSecondSpeciality());
            beSectionExpertInfo.setThirdSpeciality(beSectionExpertInfoDTO.getThirdSpeciality());
            beSectionExpertInfo.setFourSpeciality(beSectionExpertInfoDTO.getFourSpeciality());
            beSectionExpertInfo.setSex(beSectionExpertInfoDTO.getSex());
            beSectionExpertInfo.setIsIdentity("1");
            if(beSectionExpertInfoService.saveExpertInfo(beSectionExpertInfo,beSectionExpertInfoDTO.getPassword())){
            	log.info(identityThirdCheck+":IdentityThirdCheck");
            	if("1".equals(identityThirdCheck)) {
            		log.info(beSectionExpertInfoDTO+"**************IdentityThirdCheck");
            		if(beSectionExpertInfoDTO.getExpertSource()==null) {
                		return Response.fail("专家来源不能为空");
                	}
                	if(!beSectionExpertInfoDTO.getExpertSource().equals(2)) {
                		if(StringUtils.isBlank(beSectionExpertInfoDTO.getCardNo())) {
                    		return Response.fail("专家身份证号不能为空");
                    	}
                		if(StringUtils.isBlank(beSectionExpertInfoDTO.getName())) {
                    		return Response.fail("专家姓名不能为空");
                    	}
                		//建委五库-方欣
                		BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(beSectionExpertInfoDTO.getSectionId());
                    	Response<String> response = entInfoService.getExportInfo(beSectionExpertInfoDTO.getCardNo(), beSectionExpertInfoDTO.getName(), beSectionInfo.getSectionCode());
                    	if(!response.isSuccess()) {
                    		beSectionExpertInfoService.deleteBeSectionExpertInfos(beSectionExpertInfo.getSeqId());
                    		return Response.fail("专家验证失败");
                    	}
                	}
            	}
            	
                return Response.ok("保存成功");
            } else {
                return Response.fail("保存失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail(e.getMessage());
        }
    }
   
    /**
     * 调用外部系统的api接口查询专家库
     * @param cardNo
     * @return
     */
    @RequestMapping("/queryExpertInfoByCardNo")
    @ApiOperation(value = "专家设置-根据身份证号码查询专家基本库信息", response = Response.class, httpMethod = "GET")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "cardNo", value = "身份证号码", required = true),
            })
    public Response<BeExpertInfo> queryExpertInfoByCardNo(@RequestParam("cardNo") String cardNo) {
        try {
            return Response.ok(beSectionExpertInfoService.queryExpertInfoByCardNo(cardNo));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("根据身份证号码查询专家基本库信息失败");
        }
    }

    @RequestMapping("/querySectionExpertInfoById")
    @ApiOperation(value = "专家设置-根据列表主键查询专家详细信息", response = BeSectionExpertInfo.class, httpMethod = "GET")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "seqId", value = "专家列表主键", required = true),
            })
    public Response<BeSectionExpertInfo> querySectionExpertInfoById(@RequestParam("seqId") String seqId) {
        try {
            return Response.ok(beSectionExpertInfoService.querySectionExpertInfoById(seqId));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("根据列表主键查询专家详细信息失败");
        }
    }

    @RequestMapping("/getWebSocketAccessToken")
    @ApiOperation(value = "专家评标获取websocket访问权限的token", notes = "专家评标获取websocket访问权限的token", httpMethod = "GET")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "sectionId", value = "标段ID", required = true),
            })
    public Response<String> query(@RequestParam("sectionId") String sectionId) {
        try {
            String userGuid = RequestUtil.getHeader("userGuid");
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            BeSectionExpertInfo expertInfo = beSectionExpertInfoService.selectByLoginName(sectionId, tsUser.getLoginName());
            if (expertInfo == null) {
                return Response.fail("sectionId:" + sectionId + ",loginName:" + tsUser.getLoginName() + ",不存在");
            }
            if (StringUtils.isBlank(RedisUtil.get(RedisKeyConstants.webSoketToken + expertInfo.getSeqId()))) {
                RedisUtil.set(RedisKeyConstants.webSoketToken + expertInfo.getSeqId(), expertInfo.getSeqId());
                RedisUtil.expire(RedisKeyConstants.webSoketToken + expertInfo.getSeqId(), 60 * 60 * 24);
            }
            return Response.ok(expertInfo.getSeqId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("专家评标获取websocket访问权限的token失败");
        }
    }

    @RequestMapping("/deleteExpertInfos")
    @ApiOperation(value = "专家设置-根据主键删除专家信息", response = Response.class, httpMethod = "POST")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "seqIds", value = "专家列表主键（多个以逗号分割）", required = true)
            })
    public Response deleteBeSectionExpertInfos(@RequestParam("seqIds") String seqIds) {
        try {
            if(beSectionExpertInfoService.deleteBeSectionExpertInfos(seqIds)){
                return Response.ok("删除成功");
            } else {
                return Response.fail("删除失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("删除失败");
        }
    }

    @RequestMapping("/delExpertInfos")
    @ApiOperation(value = "专家设置-根据主键删除专家信息", response = Response.class, httpMethod = "POST")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "seqIds", value = "专家列表主键（多个以逗号分割）", required = true),
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "remark", value = "删除原因", required = true)
            })
    public Response delBeSectionExpertInfos(@RequestParam("seqIds") String seqIds, @RequestParam("remark") String remark) {
        try {
            beSectionExpertInfoService.delBeSectionExpertInfos(seqIds, remark);
            return Response.ok("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("删除失败");
        }
    }

    /**
     * 保存专家回避信息并更新回避状态
     * @param sectionId
     * @param reason
     * @return
     */
    @PostMapping("/updateAvoidReason")
    @ApiOperation(value = "保存专家回避信息并更新回避状态(2019-09-17-v1)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "reason", value = "回避原因", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "获取专家信息失败，请重新登录"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_THREE, message = "保存失败，请重新保存"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_FOUR, message = "保存异常"),
    })
    public Response updateAvoidReason(@RequestParam("sectionId") String sectionId, @RequestParam("reason") String reason) {
        if (StringUtils.isBlank(sectionId) || StringUtils.isBlank(reason)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        String userGuid = RequestUtil.getHeader("userGuid");
        TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
        if (tsUser != null) {
            BeSectionExpertInfo beSectionExpertInfo = new BeSectionExpertInfo();
            beSectionExpertInfo.setLoginName(tsUser.getLoginName());
            beSectionExpertInfo.setSectionId(sectionId);
            beSectionExpertInfo.setAvoidReason(reason);
            //是否回避(1是 0否)
            beSectionExpertInfo.setIsAvoid(Constants.ONE);
            beSectionExpertInfo.setUpdateTime(DateUtil.now());
            try {
                if (beSectionExpertInfoService.updateAvoidReason(beSectionExpertInfo)) {
                    return Response.ok("保存成功");
                }
                return Response.fail("保存失败，请重新保存", Constants.FIVE_HUNDRED_AND_THREE);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Response.fail("保存异常", Constants.FIVE_HUNDRED_AND_FOUR);
            }
        } else {
            return Response.fail("获取专家信息失败，请重新登录", Constants.FIVE_HUNDRED_AND_TWO);
        }
    }

    /**
     * 根据专家登录账号查询专家回避状态
     *
     * @param sectionId
     * @return
     */
    @GetMapping("/queryExpertInfoByLoginName")
    @ApiOperation(value = "根据专家登录账号查询专家信息(2019-11-24-v1)", response = BeSectionExpertInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.TWO_HUNDRED, message = "专家信息"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "获取专家信息失败，请重新登录"),
    })
    public Response<BeSectionExpertInfo> queryExpertInfoByLoginName(@RequestParam("sectionId") String sectionId) {
        if (StringUtils.isBlank(sectionId)) {
            Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        String userGuid = RequestUtil.getHeader("userGuid");
        TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
        if (tsUser != null) {
            return Response.ok(beSectionExpertInfoService.selectByLoginName(sectionId, tsUser.getLoginName()));
        } else {
            return Response.fail("获取专家信息失败，请重新登录", Constants.FIVE_HUNDRED_AND_TWO);
        }
    }


    @GetMapping("/isEnterReview")
    @ApiOperation(value = "根据专家登录账号查询专家是否可以进入评审(2019-11-11-v1)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "获取专家信息失败，请重新登录"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_THREE, message = "获取信息失败，请联系管理员"),
    })
    public Response<String> isEnterReview(@RequestParam("sectionId") String sectionId) {
        try {
            if (StringUtils.isBlank(sectionId)) {
                Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
            }
            String userGuid = RequestUtil.getHeader("userGuid");
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            if (tsUser != null) {
                return Response.ok(beSectionExpertInfoService.isEnterReview(sectionId, tsUser.getLoginName()));
            } else {
                return Response.fail("获取专家信息失败，请重新登录", Constants.FIVE_HUNDRED_AND_TWO);
            }
        } catch (BizException e) {
            log.error(e.getMessage(), e);
            return Response.fail(e.getMessage());
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("获取信息失败，请联系管理员", Constants.FIVE_HUNDRED_AND_THREE);
        }
    }

}
